var game = null
var bodyWidth = 0
var bodyHeight = 0

var phaserGame = {
    phaserInit: () => {
        bodyWidth = document.body.clientWidth
        bodyHeight = document.body.clientHeight - 200
        game = new Phaser.Game(bodyWidth, bodyHeight, Phaser.AUTO, 'fenji', {preload: preload, create: create, update: update, render: render}, true);
    },
    destroy() {
        game.destroy()
    }
}

var player;
var shipTrail;
var bullets;
var bulletTimer = 0;
var MAXSPEED = 400;

function preload() {
    game.load.image('bullet', 'assets/fjf.png');
    game.load.image('bulletb', 'assets/fjb.png');
    game.load.image('bulletj', 'assets/zfj2.png');
}

function create() {
    //  Our bullet group
    bullets = game.add.group();
    bullets.enableBody = true;
    bullets.physicsBodyType = Phaser.Physics.ARCADE;
    bullets.createMultiple(10, ['bullet', 'bulletb', 'bulletj']);
    bullets.setAll('anchor.x', 0.5);
    bullets.setAll('anchor.y', 0.5);
    // bullets.setAll('scale', 0.5)
    bullets.setAll('outOfBoundsKill', true);
    bullets.setAll('checkWorldBounds', true);

    //  The hero!
    player = game.add.sprite(bodyWidth / 2, bodyHeight / 2, 'ship');
    player.health = 100;
    
    player.anchor.setTo(0.5, 0.5);
    game.physics.enable(player, Phaser.Physics.ARCADE);
    player.body.maxVelocity.setTo(MAXSPEED, MAXSPEED);
    player.alpha = 0
}

function update() {
    fireBullet()
}

function render() {
    bullets.children.forEach(child => {
        if (child.alive) {
            if (child.scale.x >= 0) {
                child.scale.x -= 0.005
            }
            if (child.scale.y >= 0) {
                child.scale.y -= 0.005
            }
        }
    });
}

function fireBullet() {
    if (game.time.now > bulletTimer) {
        var BULLET_SPEED = 200;
        var BULLET_SPACING = 600;
        var bullet = bullets.getRandom();

        if (bullet) {
            var xPosition = Math.random() * bodyWidth
            var yPosition = Math.random() * bodyHeight
            if (xPosition < yPosition) {
                xPosition = Math.random() > 0.5 ? bodyWidth : 0
            } else {
                yPosition = Math.random() > 0.5 ? bodyHeight : 0
            }
            bullet.reset(xPosition, yPosition);
            let angel = game.math.radToDeg(game.physics.arcade.angleBetween(bullet, player))
            bullet.scale.x = 0.5
            bullet.scale.y = 0.5
            bullet.angle = angel + 45
            game.physics.arcade.velocityFromAngle(angel, BULLET_SPEED, bullet.body.velocity);
            bullet.body.velocity.x += player.body.velocity.x;
            bulletTimer = game.time.now + BULLET_SPACING;
        }
    }
}

export default phaserGame